﻿using System;
using System.Data.Entity;
using log4net;
using SmallBusinessKit.DataAccess.Interfaces;

namespace SmallBusinessKit.DataAccess
{
    public class CreateDatabaseIfNotExistsWithSeed : CreateDatabaseIfNotExists<SmallBusinessContext>
    {
        #region Properties

        private static readonly ILog _log = LogManager.GetLogger(typeof(CreateDatabaseIfNotExistsWithSeed));

        private static IXmlDataParser _xmlData;

        #endregion

        #region Methods

        public CreateDatabaseIfNotExistsWithSeed(IXmlDataParser xmlData)
        {
            _xmlData = xmlData;
        }

        protected override void Seed(SmallBusinessContext db)
        {
            base.Seed(db);

            SeedCatalogData(db);
            SeedPeopleData(db);
            SeedNewsData(db);
            SeedTestimonialData(db);
        }

        private static void SeedCatalogData(SmallBusinessContext db)
        {
            try
            {
                var graph = _xmlData.LoadCatalogGraph();

                db.Categories.AddRange(graph);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                throw;
            }
        }

        private static void SeedPeopleData(SmallBusinessContext db)
        {
            try
            {
                var data = _xmlData.ParsePeople();

                db.People.AddRange(data);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                throw;
            }
        }

        private static void SeedNewsData(SmallBusinessContext db)
        {
            try
            {
                var data = _xmlData.ParseNews();

                db.News.AddRange(data);

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                throw;
            }
        }

        private static void SeedTestimonialData(SmallBusinessContext db)
        {
            try
            {
                var data = _xmlData.ParseTestimonials();

                db.Testimonials.AddRange(data);

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }

        #endregion
    }
}

// DropCreateDatabaseAlways
// DropCreateDatabaseIfModelChanges